import Konva from 'konva'
import cloneDeep from 'lodash.clonedeep'
import { useRef, useState } from 'react'

// 自定义Hook：处理图形变换逻辑
export const useShapeTransformer = (shapes, setShapes, selectedIds) => {
  const [transformerMode, setTransformerMode] = useState(false)
  const beforeTransformShapeRef = useRef([])

  const stageRef = useRef<Konva.Stage>(null)
  const layerRef = useRef<Konva.Layer>(null)
  const groupRef = useRef<Konva.Group>(null)
  const transformerRef = useRef<Konva.Transformer>(null)

  // 开启变形模式
  const enableTransformerMode = () => {
    if (selectedIds.length === 0) return
    // 记录当前shapes, 用于撤销
    beforeTransformShapeRef.current = cloneDeep(shapes)
    setTransformerMode(true)
    transformerRef.current.nodes(selectedIds.map(id => stageRef.current.findOne(`#${id}`)))
  }

  // 确认变形
  const confirmTransform = () => {
    if (!transformerMode) return

    setTransformerMode(false)
    transformerRef.current.nodes([])
  }

  // 取消变形
  const cancelTransform = () => {
    if (!transformerMode) return

    setTransformerMode(false)
    setShapes(beforeTransformShapeRef.current)
    transformerRef.current.nodes([])
  }

  // 处理组拖拽结束事件
  const handleGroupDragStart = () => {
    groupRef.current.stopDrag()
    if (!transformerMode) return
    // 停止所有图形的拖拽，只允许选中的图形拖拽
    shapes.forEach(shape => {
      if (selectedIds.includes(shape.id)) {
        stageRef.current.findOne(`#${shape.id}`).startDrag()
      } else {
        stageRef.current.findOne(`#${shape.id}`).stopDrag()
      }
    })
  }

  // 处理变换结束事件
  const handleTransformEnd = (e: Konva.KonvaEventObject<DragEvent>, index: number) => {
    const node = e.target as Konva.Shape

    if (!node) return
    const { x, y, width, height, scaleX, scaleY, rotation } = node.attrs

    // 更新所有选中图形的属性
    setShapes(prevShapes => {
      const newShapes = cloneDeep(prevShapes)
      newShapes[index] = {
        ...newShapes[index],
        x: x,
        y: y,
        width,
        height,
        scaleX,
        scaleY,
        rotation: rotation
      }
      return newShapes
    })
  }

  // 处理图形拖拽结束事件
  const handleShapeDragEnd = (e: Konva.KonvaEventObject<DragEvent>, index: number) => {
    const node = e.target as Konva.Shape
    const { x, y } = node.position()

    setShapes(prevShapes => {
      const newShapes = cloneDeep(prevShapes)
      newShapes[index] = {
        ...newShapes[index],
        x,
        y
      }
      return newShapes
    })
  }

  return {
    transformerMode,
    stageRef,
    layerRef,
    groupRef,
    transformerRef,
    enableTransformerMode,
    confirmTransform,
    cancelTransform,
    handleGroupDragStart,
    handleTransformEnd,
    handleShapeDragEnd
  }
}
